<?php
namespace control;
/*
*资金报表类
*/

use JetBrains\PhpStorm\NoReturn;

class financialReportClass extends adIndexClass
{
    private const page = 'financialReport';
    private const table = 'bookkeeping';
    private const title = '资金报表';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'bankSearch':
                $tr = [
                    'classify'          => [
                        'name'  => "收支类别",
                        'width' => 350,
                        'sort' => 1,
                    ],
                    'income'          => [
                        'name'  => '收入总额',
                        'width' => 350,
                    ],
                    'out'          => [
                        'name'  => '支出总额',
                        'width' => 300,
                    ],
                    'incomeNum'          => [
                        'name'  => '收入笔数',
                        'width' => 300,
                    ],
                    'outNum'          => [
                        'name'  => '支出笔数',
                        'width' => 300,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "账户编码",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '账户名称',
                        'width' => 200,
                    ],
                    'initMoney'         => [
                        'name'  => '期初余额',
                        'width' => 200,
                    ],
                    'income'          => [
                        'name'  => '收入总额',
                        'width' => 200,
                    ],
                    'out'          => [
                        'name'  => '支出总额',
                        'width' => 200,
                    ],
                    'balance'          => [
                        'name'  => '余额',
                        'width' => 200,
                    ],
                    'incomeNum'          => [
                        'name'  => '收入笔数',
                        'width' => 150,
                    ],
                    'outNum'          => [
                        'name'  => '支出笔数',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "账户编码" => text(array("name" => "orderNo")),
                    "账户名称"   => text(array("name" => "name")),
                    '日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $timeWhere = '';
        $startDate='';
        if ($this->post('createTime')){
            $data = explode('~', $this->post('createTime'));
            $startDate = trim($data[0]);
            $timeWhere.=self::timeComparison($this->post('createTime'),field: 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array("table" =>'account', "where" => $where, "order" => $orderBy['orderBy']));
        static::rSet(self::$stid.self::page.'sql',$page['fullSql']);
        static::rSet(self::$stid.self::page.'time',$this->post('createTime'));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            if (empty($this->post('createTime'))){
                //没有时间筛选，只取期初
                $initMoney = $array['initMoney'];
            }else{
                //有时间筛选，取开始时间之前的余额+期初金额
                $initMoney =find(array('table'=>self::table,'single'=>"accountId = '$array[id]' and recordDate < '$startDate'",'field'=>"ifnull(sum(income-expenses),0) as money"))['money'];
                $initMoney+= $array['initMoney'];
            }
            $income = find(array('table'=>self::table,'where'=>"accountId = '$array[id]'".$timeWhere,'sum'=>"income"));
            $out =  find(array('table'=>self::table,'where'=>"accountId = '$array[id]'".$timeWhere,'sum'=>"expenses"));
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'initMoney':
                        $row[] = $initMoney;
                        break;
                    case 'income':
                        $row[] = $income;
                        break;
                    case 'out':
                        $row[] = $out;
                        break;
                    case 'balance':
                        $row[] = $initMoney+$income-$out;
                        break;
                    case 'incomeNum':
                        $incomeNum = static::total(array('table'=>self::table,'where'=>"accountId = '$array[id]' and income >0".$timeWhere));
                        $row[] = $incomeNum;
                        break;
                    case 'outNum':
                        $outNum = static::total(array('table'=>self::table,'where'=>"accountId = '$array[id]' and expenses >0".$timeWhere));
                        $row[] = $outNum;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] =
            $page['hint'] .
            $button .
            "<form name='listForm'>" .
                $li .
            "</form>" .
            $page['button'] .
            clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    #[NoReturn] public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $sql = static::rGet(self::$stid.self::page.'sql');
            $createTime = static::rGet(self::$stid.self::page.'time');
            $timeWhere='';
            $startDate='';
            if ($createTime){
                $data = explode('~', $createTime);
                $startDate = trim($data[0]);
                $timeWhere.=self::timeComparison($createTime,field: 'recordDate');
            }
            $title = array("账户编码", "账户名称", "期初余额", "收入总额", "支出总额", "余额", '收入笔数', '支出笔数');
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    if (empty($this->post('createTime'))){
                        //没有时间筛选，只取期初
                        $initMoney = $array['initMoney'];
                    }else{
                        //有时间筛选，取开始时间之前的余额+期初金额
                        $initMoney =find(array('table'=>self::table,'single'=>"accountId = '$array[id]' and recordDate < '$startDate'",'field'=>"ifnull(sum(income-expenses),0) as money"))['money'];
                        $initMoney+= $array['initMoney'];
                    }
                    $income = find(array('table'=>self::table,'where'=>"accountId = '$array[id]'".$timeWhere,'sum'=>"income"));
                    $out =  find(array('table'=>self::table,'where'=>"accountId = '$array[id]'".$timeWhere,'sum'=>"expenses"));
                    $incomeNum = static::total(array('table'=>self::table,'where'=>"accountId = '$array[id]' and income >0".$timeWhere));
                    $outNum = static::total(array('table'=>self::table,'where'=>"accountId = '$array[id]' and expenses >0".$timeWhere));
                    $tr[] = array($array['orderNo'], $array['name'], $initMoney,$income, $out,$initMoney+$income-$out, $incomeNum, $outNum);
                }
            }
            $text = $this->control['name'] . "导出了按账户分类的资金报表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, "按账户分类的资金报表.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /*列表页-查询条件*/
    public function bankOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function bank()
    {
        $html = $this->bankOptions(false);
        //控件
        $button = "";
        if ($this->power('financialReportBank', "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportDataOther'><span class='spanButton'>导出</span></a>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function bankSearch()
    {
        //like查询数组
        $like = array(
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
        );
        $timeWhere = '';
        if ($this->post('createTime')){
            $timeWhere.=self::timeComparison($this->post('createTime'),field: 'recordDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)).$timeWhere;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'classify',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => self::table,
            'field'=>"distinct classify",
            "where" => $where." and classify !='内部转账'",
            "order" => $orderBy['orderBy']
        ));
        static::rSet(self::$stid.self::page.'sql2',$page['fullSql']);
        static::rSet(self::$stid.self::page.'time2',$this->post('createTime'));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'income':
                        $income = find(array('table'=>self::table,'where'=>"classify = '$array[classify]' and coid = '".self::$coid."'".$timeWhere,'sum'=>"income"));
                        $row[] = $income;
                        break;
                    case 'out':
                        $out =  find(array('table'=>self::table,'where'=>"classify = '$array[classify]' and coid = '".self::$coid."'".$timeWhere,'sum'=>"expenses"));
                        $row[] = $out;
                        break;
                    case 'incomeNum':
                        $incomeNum = static::total(array('table'=>self::table,'where'=>"classify = '$array[classify]' and coid = '".self::$coid."' and income >0".$timeWhere));
                        $row[] = $incomeNum;
                        break;
                    case 'outNum':
                        $outNum = static::total(array('table'=>self::table,'where'=>"classify = '$array[classify]' and coid = '".self::$coid."' and expenses >0".$timeWhere));
                        $row[] = $outNum;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] =
            $page['hint'] .
            $button .
            "<form name='bankForm'>" .
                $li .
            "</form>" .
            $page['button'] .
            clear;
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    #[NoReturn] public function exportDataOther()
    {
        if (!$this->power('financialReportBank', 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr = [];
            $sql = static::rGet(self::$stid.self::page.'sql2');
            $createTime = static::rGet(self::$stid.self::page.'time2');
            $timeWhere = '';
            if ($createTime) {
                $timeWhere .= self::timeComparison($createTime, field: 'recordDate');
            }
            $title = array("收支类别", "收入总额", "支出总额", "收入笔数", "支出笔数");
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $income = find(array('table'=>self::table,'where'=>"classify = '$array[classify]' and coid = '".self::$coid."'".$timeWhere,'sum'=>"income"));
                    $out =  find(array('table'=>self::table,'where'=>"classify = '$array[classify]' and coid = '".self::$coid."'".$timeWhere,'sum'=>"expenses"));
                    $incomeNum = static::total(array('table'=>self::table,'where'=>"classify = '$array[classify]' and coid = '".self::$coid."' and income >0".$timeWhere));
                    $outNum = static::total(array('table'=>self::table,'where'=>"classify = '$array[classify]' and coid = '".self::$coid."' and expenses >0".$timeWhere));
                    $tr[] = array($array['classify'],$income,$out, $incomeNum, $outNum);
                }
            }
            $text = $this->control['name'] . "导出了按收支类型分类的资金报表";
            $this->logText(["type" => 'financialReportBank', "text" => $text]);
            $this->excelOut($title, $tr, "按收支类型分类的资金报表.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

}

